﻿using FlyingEye.Common.Utils;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Modularity;

namespace FlyingEye.EntityFrameworkCore
{
    [DependsOn(typeof(Volo.Abp.Autofac.AbpAutofacModule))]
    [DependsOn(typeof(FlyingEye.FlyingEyeDomainModule))]
    [DependsOn(typeof(Volo.Abp.EntityFrameworkCore.MySQL.AbpEntityFrameworkCoreMySQLModule))]
    public class MySqlEntityFrameworkCoreModule : AbpModule
    {
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            MySqlEfCoreEntityExtensionMappings.Configure();
            base.PreConfigureServices(context);
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            // 注册数据库上下文。
            context.Services.AddAbpDbContext<MySqlDbContext>();

            // 配置数据库连接字符串。
            // 回调在调用数据库读写时才会调用，所以此时获取 ApplicationConfiguration 服务的依赖已经全部初始化完成
            Configure<AbpDbConnectionOptions>(options =>
            {
                var priavteKey = options.ConnectionStrings["PrivateKey"];
                var service = context.Services.BuildServiceProvider();
                var configuration = service.GetRequiredService<ApplicationConfiguration>();
                var defaultString = configuration.GetMySqlConnectionString("Default");
                var testString = configuration.GetMySqlConnectionString("TestMySql");
                var localString = configuration.GetMySqlConnectionString("LocalMySql");
                options.ConnectionStrings.Default = defaultString;
                options.ConnectionStrings["TestMySql"] = testString;
                options.ConnectionStrings["LocalMySql"] = localString;
                options.ConnectionStrings["MySql"] = defaultString;
            });

            Configure<AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });

            base.ConfigureServices(context);
        }
    }
}
